#!/usr/bin/python
# Copyright (C) 2003, Charles Wang.
# Author:  Charles Wang <charles@linux.net.cn>
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANT; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public LIcense for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA.

import os
import sys

cmds = []
todir = sys.argv[1]

# Create the required directories and some files.
cpcmd = 'cp -a --no-preserve=ownership'
mountpoints = "root.mnt,root.cramfs.mnt,device.mnt,mnt1,mnt2,mnt3"
cmds.append('mkdir -p %s/{dev,etc,proc,tmp}' % todir)
cmds.append('mkdir -p %s/var/log' % todir)
cmds.append('mkdir -p %s/tmp/{%s}' % (todir, mountpoints))
cmds.append('%s /dev/ram[01] /dev/loop[4-7] %s/dev' % (cpcmd, todir))
cmds.append('%s /dev/sd[a-h] /dev/sd[a-h][1-9] /dev/sd[a-h]1[0-9] %s/dev' % (cpcmd, todir))
cmds.append('%s /dev/hd[a-h]* %s/dev' % (cpcmd, todir))

# Create the required device files.
for d in ['console', 'null', 'zero',
          'tty', 'tty1', 'tty2', 'tty3', 'tty4', 'tty5', 'tty6']:
    cmds.append('%s /dev/%s %s/dev' % (cpcmd, d, todir))

# Remove .sconsign
cmds.append('find %s -name .sconsign | xargs rm -f' % todir)

# Link 'linuxrc' to 'bin/magicbooter'.
# Refer the README in magicbooter directory before add/remove of the included applets.
bin_links = ['cpio', 'gunzip', 'mount', 'sh', 'umount']
sbin_links = ['ifconfig', 'init', 'insmod', 'modprobe', 'rmmod', 'route']
usrbin_links = ['wget']
cmds.append('mkdir -p %s %s %s' % \
            (os.path.join(todir, 'bin'),
             os.path.join(todir, 'sbin'),
             os.path.join(todir, 'usr/bin')))
for link in bin_links:
    cmds.append('ln -s ../sbin/magicbooter %s' % \
                os.path.join(todir, 'bin', link))
for link in sbin_links:
    cmds.append('ln -s magicbooter %s' % \
                os.path.join(todir, 'sbin', link))
for link in usrbin_links:
    cmds.append('ln -s ../../sbin/magicbooter %s' % \
                os.path.join(todir, 'usr/bin', link))

for cmd in cmds:
    print cmd
    if os.system(cmd) != 0:
        sys.exit(1)
